//
//  SettingController.m
//  CMYH
//
//  Created by Loki on 15-5-13.
//  Copyright (c) 2015年 Loki. All rights reserved.
//

#import "SettingController.h"
#import "X.h"
#import "Define.h"
#import "Busi.h"


const int TAG_ENSURE                                        = 1001;


@interface SettingController () <BusiDelegate>
@property (nonatomic, assign) NSInteger                     nIndex;
@property (nonatomic, assign) NSInteger                     nDeleteIndex;
@property (nonatomic, strong) NSMutableArray                *servers;
@end


@implementation SettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _nDeleteIndex = -1;
    
    CGRect rc = _vHistory.frame;
    rc.size.height -= 68;
    _vHistory.frame = rc;
    
    // 读取IP地址
    NSString *strVal = [XUser stringForKey:kServerAddress];
    if ([strVal length] > 0) {
        [_txtIPAddress setText:strVal];
    }
    
    // 读取IP地址列表
    NSMutableArray *server = [[NSMutableArray alloc] initWithArray:(NSArray *) [XUser objectForKey:kServerAddressList]];
    if (server.count == 0) {
        // 没有服务器地址，初始化地址
        server = [[NSMutableArray alloc] initWithObjects:@"192.168.2.33", @"192.168.13.30",
                  @"192.168.14.30", @"192.168.17.30", @"192.168.18.30", @"192.168.19.30",
                  @"192.168.11.30", nil];
    }
    else {
        // 有服務器配置，把含有空格的地址信息刪除
        NSMutableArray *arrDel = [[NSMutableArray alloc] initWithCapacity:0];
        for (NSString *strAddr in server) {
            if (strAddr.length == 0) {
                [arrDel addObject:strAddr];
            }
            else if ([strAddr containsString:@" "]) {
                [arrDel addObject:strAddr];
            }
        }
        [server removeObjectsInArray:arrDel];
    }
    _servers = [[NSMutableArray alloc] initWithCapacity:0];
    [_servers setArray:server];
    
    UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(deleteServerAddress:)];
    longPressGr.minimumPressDuration = 1.0;
    [_tbHistory addGestureRecognizer:longPressGr];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 */


/**
 * 检测处理
 * @return
 */
- (void)detect {
    // 处理服务器保存
    NSString *strServer = [_servers objectAtIndex:_nIndex];
    [XUser setString:strServer forKey:kServerAddress];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.timeout = 8;
    req.method = @"HelloWorld";
    [req query];
}


- (IBAction)onAutoDetect:(id)sender {
    if (_servers.count > 0) {
        // 显示等待
        [XMsg showProgress];
        
        // 处理自动检测
        _nIndex = 0;
        
        // 处理检测
        [self detect];
    }
    else {
        [XMsg showToast:@"請先錄入用於自動檢測的服務器地址！"
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
}


- (IBAction)onSave:(id)sender {
    if (_txtIPAddress.text.length == 0) {
        [XMsg showToast:@"服務器地址不能為空，請重新輸入！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        return;
    }
    else if ([_txtIPAddress.text containsString:@" "]) {
        [XMsg showToast:@"服務器地址不能含有空格，請重新輸入！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        return;
    }
    
    [_txtIPAddress resignFirstResponder];
    
    // 保存成默认设置
    [XUser setString:_txtIPAddress.text forKey:kServerAddress];
    
    // 添加到列表当中
    if ([_servers indexOfObject:_txtIPAddress.text] == NSNotFound) {
        [_servers insertObject:_txtIPAddress.text atIndex:0];
        [XUser setObject:_servers forKey:kServerAddressList];
        
        // 刷新列表数据
        [_tbHistory reloadData];
    }
}


- (void)onBackgroundTouch {
    [_txtIPAddress resignFirstResponder];
}


- (void) deleteServerAddress:(UILongPressGestureRecognizer*)longPr {
    if(longPr.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [longPr locationInView:_tbHistory];
        NSIndexPath *indexPath = [_tbHistory indexPathForRowAtPoint:point];
        if(indexPath != nil) {
            _nDeleteIndex = indexPath.row;
            [XMsg showMessage:@"是否刪除該服務器地址？"
                    withTitle:@"溫馨提示"
                          tag:TAG_ENSURE
                           ok:@"是"
                       cancel:@"否"
                     delegate:self];
        }
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _servers == nil ? 0 : _servers.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 获取或创建 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"server-address"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:@"server-address"];
    }
    
    // 获取对应的服务器地址，加入到列表当中
    NSString *strServer = [_servers objectAtIndex:indexPath.row];
    [[cell textLabel] setText:strServer];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 保存成默认设置
    NSString *strServer = [_servers objectAtIndex:indexPath.row];
    _txtIPAddress.text = strServer;
    [XUser setString:strServer forKey:kServerAddress];
    
    // 调整列表当中的次序
    [_servers removeObject:strServer];
    [_servers insertObject:strServer atIndex:0];
    [XUser setObject:_servers forKey:kServerAddressList];
    
    // 刷新列表
    [_tbHistory reloadData];
}


#pragma mark BusiDelegate
- (void)requestException:(NSException *)exception withID:(NSString *)reqID {
    if ([reqID isEqualToString:@"HelloWorld"]) {
        // 当前地址不可用，继续尝试下一个地址
        if (_nIndex + 1 < _servers.count) {
            ++_nIndex;
            NSString *strServer = [_servers objectAtIndex:_nIndex];
            [XUser setString:strServer forKey:kServerAddress];
            
            // 处理检测
            Busi *req = [[Busi alloc] init];
            req.delegete = self;
            req.timeout = 8;
            req.method = @"HelloWorld";
            [req query];
        }
        else {
            [XMsg hideProgress];
            [XMsg showToast:@"列表中沒有檢測到可用的服務器！請配置可用的服務器地址！"
                withGravity:AlignTop
                andDuration:DurationNormal];
        }
    }
}


- (void)requestFinished:(NSObject *)res withHeaders:(NSDictionary *)headers andID:(NSString *)reqID {
    if ([reqID isEqualToString:@"HelloWorld"]) {
        bool bRet = false;
        NSDictionary *dicRes = (NSDictionary *) res;
        do {
            NSDictionary *dicEnvelope = [dicRes objectForKey:@"soap:Envelope"];
            if (dicEnvelope == nil) {
                break;
            }
            
            NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
            if (dicBody == nil) {
                break;
            }
            
            NSDictionary *dicResponse = [dicBody objectForKey:@"HelloWorldResponse"];
            if (dicResponse == nil) {
                break;
            }
            
            NSDictionary *dicResult = [dicResponse objectForKey:@"HelloWorldResult"];
            if (dicResult == nil) {
                break;
            }
            
            NSString *strHelloworld = [dicResult objectForKey:kValue];
            if (strHelloworld != nil && [strHelloworld isEqualToString:@"Hello World"]) {
                // 检测成功
                bRet = true;
            }
        } while (0);
        
        if (!bRet) {
            // 当前地址不可用，继续尝试下一个地址
            if (_nIndex + 1 < _servers.count) {
                ++_nIndex;
                [self detect];
            }
            else {
                [XMsg hideProgress];
                [XMsg showToast:@"列表中沒有檢測到可用的服務器！請配置可用的服務器地址！"
                    withGravity:AlignTop
                    andDuration:DurationNormal];
            }
        }
        else {
            [XMsg hideProgress];
            // 保存成默认设置
            NSString *strServer = [_servers objectAtIndex:_nIndex];
            _txtIPAddress.text = strServer;
            [XUser setString:strServer forKey:kServerAddress];
            
            // 调整列表当中的次序
            [_servers removeObject:strServer];
            [_servers insertObject:strServer atIndex:0];
            [XUser setObject:_servers forKey:kServerAddressList];
            
            // 刷新列表
            [_tbHistory reloadData];
            
            // 显示提示信息
            [XMsg showToast:@"已檢測到可用地址！"
                withGravity:AlignTop
                andDuration:DurationNormal];
        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == TAG_ENSURE) {
        if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"是"] && _nDeleteIndex != -1) {
            [_servers removeObjectAtIndex:_nDeleteIndex];
            [XUser setObject:_servers forKey:kServerAddressList];
            [_tbHistory reloadData];
            _nDeleteIndex = -1;
        }
    }
}


@end
